package app.caihan.wanandroid.ui.wxarticle

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import app.caihan.scframe.api.retrofit2.checkResult
import app.caihan.scframe.constant.DEBUG_TAG
import app.caihan.wanandroid.base.WanBaseViewModel
import app.caihan.wanandroid.model.ScWanAndroidFactory
import app.caihan.wanandroid.model.bean.PageList
import com.blankj.utilcode.util.LogUtils
import com.scwang.smart.refresh.layout.api.RefreshLayout


class ChapterFragmentModel : WanBaseViewModel() {

    private val repository by lazy { ScWanAndroidFactory.makeWanRepository() }

    private var chaptersId: Int = 0

    // 私有的 MutableLiveData 可变的，对内访问
    private val _chapterArticleList: MutableLiveData<PageList> by lazy {
        MutableLiveData<PageList>()
    }

    // 对外暴露不可变的 LiveData，只能查询
    val chapterArticleList: LiveData<PageList> = _chapterArticleList

    val onRefreshListener: (RefreshLayout) -> Unit = {
        launchUI {
            getWxArticleList(true)
        }
    }

    val onLoadMoreListener: (RefreshLayout) -> Unit = {
        launchUI {
            getWxArticleList(false)
        }
    }

    suspend fun getWxArticleList(isRefresh: Boolean = false) {
        var page = 1
        if (!isRefresh) {
            _chapterArticleList.value?.apply {
                page = curPage + 1
            }
        }
        repository.getWxArticleList(chaptersId, page)
            .checkResult(
                onSuccess = {
                    _chapterArticleList.value = it
                }, onError = {
                    LogUtils.dTag(DEBUG_TAG, "getWxArticleList onError $it")
                }
            )
        finishRefresh(_chapterArticleList.value)
    }

    fun autoRefresh(id: Int) {
        chaptersId = id
        launchUI {
            showLoadingView()
            getWxArticleList(true)
            showContentView()
        }
    }

}